import React, { useState, useEffect, useImperativeHandle, forwardRef } from 'react';
import { Select, Input, Checkbox, Button, message } from 'antd';
import ConfigTable from '../../../../components/configTable';
import { POSITION, TYPE_OPTIONS } from '../../../../../../utils/constant';
import Modal from '../../../../../../components/Modal';
import EnterParamMore from '../../../components/Add/moreParam';
import { cloneDeep, flattenDepth } from 'lodash';
import services from '../../../../../../services/api';

let selectParamsIdList = [];

const EnterParam = forwardRef((props, ref) => {
  const { value } = props;
  const [data, setData] = useState([]);

  let defaultData = {
    position: 1,
    type: 0,
    nonEmpty: 0,
    thirdParamList: [],
  };

  useEffect(() => {
    // 将后端数据转为前使用的数据
    value.params && getTransferUseData(value.params);
  }, [value.params]);

  useEffect(() => {
    const { thirdList, changeObj } = value;
    const tempData = cloneDeep(data);
    // 三方数据源改变 则入参数数据源选择也要相应改变
    const interfaceAllList = thirdList.map(({ id, name }) => ({
      id,
      name,
    }));
    tempData.forEach((item) => {
      item['interfaceAllList'] = interfaceAllList;
    });
    if (changeObj) {
      // 删除
      if (changeObj.length === 1) {
        const deleteId = changeObj[0];
        tempData.forEach((item, index) => {
          item.thirdParamList.forEach((val, tIndex) => {
            if (val.interfaceId === deleteId) {
              if (item.thirdParamList.length === 1) {
                tempData.splice(index, 1);
              } else {
                item.thirdParamList.splice(tIndex, 1);
              }
            }
          });
        });
      }
      // 改变
      if (changeObj.length === 2) {
        const [newId, oldId] = changeObj;
        tempData.forEach((item) => {
          item.thirdParamList.forEach((el, tIndex) => {
            if (el.interfaceId === oldId) {
              const { id, params } = thirdList.find((item) => item.id === newId);
              const tempObj = {
                interfaceId: id,
                paramsList: params,
                paramId: '',
                tpPositionLabel: undefined,
                tpTypeLabel: undefined,
              };
              item.thirdParamList[tIndex] = tempObj;
            }
          });
        });
      }
    }
    setData(tempData);
  }, [value.thirdList]);

  const getTransferUseData = async (data) => {
    const tempData = cloneDeep(data);
    const { thirdInterfaceList } = value;
    for (const item of thirdInterfaceList) {
      const {
        data: { params },
      } = await services.dataSource.detail(item.id);
      item.params = params;
    }
    tempData.forEach((item) => {
      item.thirdParamList.forEach((item) => {
        item['paramId'] = item.id;
        item['paramsList'] = thirdInterfaceList.find((val) => val.id === item.interfaceId).params;
      });
    });
    setData(tempData);
  };

  useImperativeHandle(ref, () => ({
    getData: () => {
      if (!data.length) {
        throw '请添加数据源入参';
      }
      data.forEach((item) => {
        if (!item.name) {
          throw '请填写数据源入参参数名';
        }
        item.thirdParamList.forEach((item) => {
          if (!item.paramId) {
            throw '请选择数据源入参对应数据源参数名';
          }
        });
      });
      return data;
    },
  }));

  // 添加
  const handleAdd = () => {
    // 展示数据源
    const { thirdList } = value;
    const tempData = cloneDeep(data);
    if (!thirdList.length) return message.warning('请添加数据源！');
    defaultData.interfaceAllList = thirdList.map(({ id, name }) => ({
      id,
      name,
    }));
    defaultData.thirdParamList = thirdList.map(({ id, params }) => ({
      interfaceId: id,
      paramId: '',
      paramsList: params,
    }));
    tempData.push(cloneDeep(defaultData));
    setData(tempData);
  };

  const handleChange = (value, index, key) => {
    const tempData = cloneDeep(data);
    if (key === 'name') {
      const new_value = value.match(/[0-9a-zA-Z_.]{1,}/);
      tempData[index][key] = new_value ? new_value[0] : '';
      return setData(tempData);
    }
    tempData[index][key] = value;
    setData(tempData);
  };

  // 选择数据源
  const handleInterfaceChange = (value, index, tIndex) => {
    const { thirdList } = value;
    const tempData = cloneDeep(data);
    const paramsList = thirdList.find((item) => item.id === value).params;
    const tempObj = {
      interfaceId: value,
      paramId: undefined,
      positionLabel: undefined,
      typeLabel: undefined,
      paramsList,
    };
    tempData[index].thirdParamList[tIndex] = tempObj;
    setData(tempData);
  };

  // 禁用已选择的数据源
  const hanleVisibleChange = (value, index) => {
    if (value) {
      const tempData = cloneDeep(data);
      const { interfaceAllList, thirdParamList } = tempData[index];
      const interfaceIdList = thirdParamList.map((item) => item.interfaceId);
      const tempList = interfaceAllList.map((item) => {
        item.disabled = false;
        if (interfaceIdList.includes(item.id)) {
          item.disabled = true;
        }
        return item;
      });
      tempData[index]['interfaceAllList'] = tempList;
      setData(tempData);
    }
  };

  // 选择出参显示相应的 位置  类型
  const handleNameChange = (paramId, index, tIndex) => {
    const tempData = cloneDeep(data);
    const targetObj = tempData[index].thirdParamList[tIndex];
    const { positionLabel, typeLabel } = targetObj.paramsList.find((item) => item.id === paramId);
    const tempObj = {
      paramId,
      positionLabel,
      typeLabel,
    };
    tempData[index].thirdParamList[tIndex] = {
      ...targetObj,
      ...tempObj,
    };
    // 获取当前选中的所有出参数id
    selectParamsIdList = flattenDepth(tempData.map((item) => item.thirdParamList.map((item) => item.paramId)));
    setData(tempData);
  };

  // 禁用已选择的参数
  const handleNameVisibleChange = (value, index, tIndex) => {
    if (value) {
      const tempData = cloneDeep(data);
      const tempParamsList = tempData[index].thirdParamList[tIndex].paramsList;
      const tempList = tempParamsList.map((item) => {
        item.disabled = false;
        if (selectParamsIdList.includes(item.id)) {
          item.disabled = true;
        }
        return item;
      });
      tempData[index].thirdParamList[tIndex].paramsList = tempList;
      setData(tempData);
    }
  };

  // 添加数据源
  const handleAddDataSource = (index) => {
    const tempData = cloneDeep(data);
    const { thirdList } = value;
    const { thirdParamList } = tempData[index];
    const interfaceIdList = thirdParamList.map((item) => item.interfaceId);
    const addIdList = thirdList.map((item) => item.id).filter((item) => !interfaceIdList.includes(item));
    if (!addIdList.length) {
      return message.warning('没有可添加的数据源！');
    }
    const paramsList = thirdList.find((item) => item.id === addIdList[0]).params;
    const tIndex = interfaceIdList.length;
    const temObj = {
      paramsList,
      interfaceId: addIdList[0],
    };
    thirdParamList[tIndex] = temObj;
    setData(tempData);
  };

  // 删除数据源
  const handleDeleteDataSource = (index, tIndex) => {
    const tempData = cloneDeep(data);
    tempData[index].thirdParamList.splice(tIndex, 1);
    setData(tempData);
  };

  const cusColumns = [
    {
      title: '参数名',
      dataIndex: 'name',
      render: (text, _, index) => (
        <Input
          value={text}
          maxLength={50}
          placeholder='请输入'
          onChange={(e) => handleChange(e.target.value, index, 'name')}
        />
      ),
    },
    {
      title: '参数位置',
      dataIndex: 'position',
      render: (text, _, index) => (
        <Select placeholder='请选择' value={text} onChange={(value) => handleChange(value, index, 'position')}>
          {POSITION.map((item) => (
            <Select.Option value={item.value} key={item.value}>
              {item.label}
            </Select.Option>
          ))}
        </Select>
      ),
    },
    {
      title: '类型',
      dataIndex: 'type',
      render: (text, _, index) => (
        <Select placeholder='请选择' value={text} onChange={(value) => handleChange(value, index, 'type')}>
          {TYPE_OPTIONS.map((item, index) => (
            <Select.Option value={index} key={index}>
              {item}
            </Select.Option>
          ))}
        </Select>
      ),
    },
    {
      title: '必填',
      dataIndex: 'nonEmpty',
      width: 80,
      render: (text, _, index) => (
        <Checkbox checked={!text} onChange={(e) => handleChange(e.target.checked ? 0 : 1, index, 'nonEmpty')} />
      ),
    },
    {
      title: '描述',
      dataIndex: 'desc',
      render: (text, _, index) => (
        <Input
          value={text}
          maxLength={256}
          placeholder='不超过256字符'
          onChange={(e) => handleChange(e.target.value, index, 'desc')}
        />
      ),
    },
    {
      title: '数据源接口',
      dataIndex: 'thirdParamList.interfaceId',
      render: (_, { thirdParamList, interfaceAllList }, index) =>
        thirdParamList &&
        thirdParamList.map((item, tIndex) => (
          <Select
            key={tIndex}
            style={{ margin: '5px 0' }}
            placeholder='请选择'
            value={item.interfaceId}
            onChange={(value) => handleInterfaceChange(value, index, tIndex)}
            onDropdownVisibleChange={(value) => hanleVisibleChange(value, index, tIndex)}
          >
            {interfaceAllList &&
              interfaceAllList.map((item) => (
                <Select.Option value={item.id} key={item.id} disabled={item.disabled}>
                  {item.name}
                </Select.Option>
              ))}
          </Select>
        )),
    },
    {
      title: '对应参数名',
      dataIndex: 'thirdParamList.paramId',
      width: 120,
      render: (_, { thirdParamList }, index) =>
        thirdParamList &&
        thirdParamList.map((item, tIndex) => (
          <Select
            key={tIndex}
            style={{ margin: '5px 0' }}
            placeholder='请选择'
            value={item.paramId}
            onChange={(value) => handleNameChange(value, index, tIndex)}
            onDropdownVisibleChange={(value) => handleNameVisibleChange(value, index, tIndex)}
          >
            {item.paramsList &&
              item.paramsList.map((item) => (
                <Select.Option value={item.id} key={item.id} disabled={item.disabled}>
                  {item.name}
                </Select.Option>
              ))}
          </Select>
        )),
    },
    {
      title: '对应参数位置',
      dataIndex: 'thirdParamList.positionLabel',
      width: 120,
      render: (_, { thirdParamList }) =>
        thirdParamList && thirdParamList.map((item, index) => <p key={index}>{item.positionLabel}</p>),
    },
    {
      title: '对应类型',
      dataIndex: 'thirdParamList.typeLabel',
      width: 120,
      render: (_, { thirdParamList }) =>
        thirdParamList && thirdParamList.map((item, index) => <p key={index}>{item.typeLabel}</p>),
    },
    {
      title: '数据源操作',
      dataIndex: 'thirdParamList.action',
      width: 120,
      render: (_, { thirdParamList }, index) =>
        thirdParamList &&
        thirdParamList.map((_, tIndex) => (
          <div key={tIndex}>
            {!tIndex ? (
              <Button type='link' onClick={() => handleAddDataSource(index, tIndex)}>
                添加
              </Button>
            ) : (
              <Button type='link' onClick={() => handleDeleteDataSource(index, tIndex)}>
                删除
              </Button>
            )}
          </div>
        )),
    },
  ];

  const handleMore = (record, index) => {
    Modal.open({
      title: '更多',
      width: '660px',
      content: (
        <EnterParamMore
          value={record}
          closeModal={() => Modal.close()}
          onChange={(value) => handleMoreChange(value, index)}
        />
      ),
      isOkBtn: false,
      isCancelBtn: false,
    });
  };

  const handleMoreChange = (value, index) => {
    const tempData = [...data];
    tempData[index] = { ...tempData[index], ...value };
    setData(tempData);
  };

  const cusOperates = [{ label: '更多', method: handleMore }];

  return (
    <>
      <Button onClick={handleAdd}>添加</Button>
      <ConfigTable
        isAdd={false}
        data={data}
        onChange={setData}
        cusColumns={cusColumns}
        cusOperates={cusOperates}
        defaultData={defaultData}
        scroll={{ x: 1300 }}
      />
    </>
  );
});
export default EnterParam;
